package sparseArray;

public class SparseArray {
    public static void main(String[] args) {
        //初始化数组 11*11
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[3][4] = 1;
        //打印原始数组
        System.out.println("原始数组");
        for (int[] rows : chessArr1) {
            for (int data : rows) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        //将二维数组转成稀疏数组
        int sum = 0;
        //遍历数组 看看有多少个非零数据
        for (int[] rows : chessArr1) {
            for (int data : rows) {
                if(data != 0){
                    sum++;
                }
            }
        }
        //创建稀疏数组
        int[][] sparseArr = new int[sum+1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        int count = 1;
        //遍历二维数组 将非0值存储到稀疏数组中
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if(chessArr1[i][j] != 0){
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                    count++;
                }
            }
        }
        //打印稀疏数组
        System.out.println("稀疏数组");
        for (int[] rows : sparseArr) {
            for (int data : rows) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        //将稀疏数组恢复成二维数组
        //先读取稀疏数组第一行
        int row = sparseArr[0][0];
        int col = sparseArr[0][1];
        int num = sparseArr[0][2];
        int[][] chessArr2 = new int[row][col];
        for (int i = 1; i < num+1; i++) {
            //遍历稀疏数组，还原二维数组
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        //打印恢复后的二维数组
        System.out.println("恢复后的二维数组");
        for (int[] rows : chessArr2) {
            for (int data : rows) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

    }
}
